package com.example.archive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.archive.entity.Tag;
import com.example.archive.mapper.TagMapper;
import com.example.archive.service.TagService;
import com.example.archive.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Override
    public Result<Boolean> addTag(Tag tag) {
        if (tag.getTagName() == null || tag.getTagName().isEmpty()) {
            return Result.fail(400, "标签名称不能为空");
        }
        QueryWrapper<Tag> query = new QueryWrapper<>();
        query.eq("tag_name", tag.getTagName());
        if (tagMapper.selectOne(query) != null) {
            return Result.fail(400, "标签名称已存在");
        }
        tag.setCreatedAt(new Date());
        int insert = tagMapper.insert(tag);
        return insert > 0 ? Result.success(true) : Result.fail(500, "添加标签失败");
    }

    @Override
    public Result<Boolean> updateTag(Tag tag) {
        if (tag.getTagId() == null) {
            return Result.fail(400, "标签ID不能为空");
        }
        if (tag.getTagName() == null || tag.getTagName().isEmpty()) {
            return Result.fail(400, "标签名称不能为空");
        }
        QueryWrapper<Tag> query = new QueryWrapper<>();
        query.eq("tag_name", tag.getTagName());
        Tag existingTag = tagMapper.selectOne(query);
        if (existingTag != null && !existingTag.getTagId().equals(tag.getTagId())) {
            return Result.fail(400, "标签名称已存在");
        }
        int update = tagMapper.updateById(tag);
        return update > 0 ? Result.success(true) : Result.fail(500, "更新标签失败");
    }

    @Override
    public Result<Boolean> deleteTag(Integer tagId) {
        if (tagId == null) {
            return Result.fail(400, "标签ID不能为空");
        }
        int delete = tagMapper.deleteById(tagId);
        return delete > 0 ? Result.success(true) : Result.fail(500, "删除标签失败");
    }

    @Override
    public Result<List<Tag>> listTags(String search) {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        if (search != null && !search.isEmpty()) {
            queryWrapper.like("tag_name", search).or().like("description", search);
        }
        List<Tag> tags = tagMapper.selectList(queryWrapper);
        return Result.success(tags);
    }
} 